"""
测试程序模板
"""
import sys

from PyQt5 import QtWidgets  # pylint: disable=W0611
from PyQt5 import QtCore  # pylint: disable=W0611
from PyQt5 import QtGui  # pylint: disable=W0611


class CustomItem(QtWidgets.QFrame):
    sizeHintChanged = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super(CustomItem, self).__init__(parent)

        self.grid = QtWidgets.QGridLayout()
        self.grid.setContentsMargins(0, 0, 0, 0)
        self.grid.setSpacing(0)
        self.grid.setColumnStretch(0, 12)
        self.grid.setColumnStretch(1, 18)
        self.grid.setColumnStretch(2, 60)
        self.grid.setColumnStretch(3, 10)
        self.setLayout(self.grid)


class CustomItemHeader(CustomItem):

    def __init__(self, parent=None):
        super(CustomItemHeader, self).__init__(parent)
        self.grid.setContentsMargins(0, 8, 0, 8)
        self.grid.addWidget(QtWidgets.QLabel("书名"), 0, 0, 1, 1)
        self.grid.addWidget(QtWidgets.QLabel("作者"), 0, 1, 1, 1)
        self.grid.addWidget(QtWidgets.QLabel("简介"), 0, 2, 1, 1)

        self.setStyleSheet('''
                QFrame {
                    background-color: rgb(255,255,255);
                }''')


class CustomItemContent(CustomItem):

    def __init__(self, item_data, parent=None):
        super(CustomItemContent, self).__init__(parent)
        self.item_data = item_data
        self.item_data["expend"] = False

        name_label = QtWidgets.QLabel(self.item_data["name"])
        self.grid.addWidget(name_label, 0, 0, 1, 1)

        auth_label = QtWidgets.QLabel(self.item_data["auth"])
        self.grid.addWidget(auth_label, 0, 1, 1, 1)

        info_label = QtWidgets.QLabel(self.item_data["info"])
        self.grid.addWidget(info_label, 0, 2, 1, 1)

        more_button = QtWidgets.QPushButton("更多")
        self.grid.addWidget(more_button, 0, 3, 1, 1)
        more_button.clicked.connect(self.more_btn_clicked)

        self.detail_label = QtWidgets.QLabel(self.item_data["detail"])
        self.grid.addWidget(self.detail_label, 1, 1, 1, 3)
        self.detail_label.setVisible(False)

    def more_btn_clicked(self):
        if self.item_data["expend"] is False:
            self.item_data["expend"] = True
            self.detail_label.setVisible(True)
        else:
            self.item_data["expend"] = False
            self.detail_label.setVisible(False)

        self.sizeHintChanged.emit()


class CustomDelegate(QtWidgets.QStyledItemDelegate):

    def __init__(self):
        super(CustomDelegate, self).__init__()
        self._editor = {}

    def createEditor(self, parent, option, index):  # pylint: disable=C0103
        # if index.row() == 0:
        #     editor = CustomItemHeader(parent)
        # else:
        #     editor = CustomItemContent(index.data(
        #         QtCore.Qt.EditRole), parent=parent)
        #     editor.setProperty("class", "content")

        editor = CustomItemContent(index.data(
            QtCore.Qt.EditRole), parent=parent)
        editor.sizeHintChanged.connect(
            lambda: self.sizeHintChanged.emit(index))
        self._editor[index.row()] = editor
        return editor

    def sizeHint(self, option, index):  # pylint: disable=C0103
        if index.row() in self._editor:
            return self._editor[index.row()].sizeHint()
        return super(CustomDelegate, self).sizeHint(option, index)

    def updateEditorGeometry(self, editor, option, index):  # pylint: disable=C0103
        super(CustomDelegate, self).updateEditorGeometry(editor, option, index)
        # if index.row() == 0:
        #     self.updateHeaderPosition()

    # def updateHeaderPosition(self):  # pylint: disable=C0103
    #     header = self._editor[0]
    #     header.raise_()
    #     header.move(0, 0)


class CustomModel(QtCore.QAbstractListModel):

    def __init__(self, parent=None):
        super(CustomModel, self).__init__(parent)
        self.model_data = [
            {"name": "《论语》", "auth": "孔子", "info": "论语", "detail": '''《论语》由孔子弟子及再传弟子编写而成，至战国前期成书。
主要记录孔子及其弟子的言行，较为集中地反映了孔子的思想，
是儒家学派的经典著作之一。以语录体为主，叙事体为辅，
集中体现了孔子的政治主张、伦理思想、道德观念及教育原则等。
与《大学》《中庸》《孟子》并称“四书”，与《诗经》等“五经”，总称“四书五经”。
全书共20章、492篇，首创 “语录体” 。
是中国现代传扬并学习的古代著作之一。'''},
            {"name": "《三国演义》", "auth": "罗贯中", "info": "三个国家的故事", "detail": '''《三国演义》是中国古典四大名著之一，是中国第一部长篇章回体历史演义小说，
全名为《三国志通俗演义》（又称《三国志演义》），
作者是元末明初的著名小说家罗贯中。
《三国志通俗演义》成书后有嘉靖壬午本等多个版本传于世，到了明末清初，毛宗岗对《三国演义》整顿回目、
修正文辞、改换诗文'''},
            {"name": "《水浒传》", "auth": "未知", "info": "一群人的故事", "detail": '''《水浒传》是由中央电视台与中国电视剧制作中心联合出品的43集电视连续剧，
根据明代施耐庵的同名小说改编。 
[1]  由张绍林执导，杨争光 、冉平改编，李雪健、周野芒、臧金生、
丁海峰、赵小锐领衔主演。'''}]

    def add_data(self, data):
        self.beginInsertRows(QtCore.QModelIndex(),
                             self.rowCount(), self.rowCount() + 1)
        self.model_data.append(data)
        self.endInsertRows()
        return self.createIndex(self.rowCount() - 1, 0)

    def data(self, index, role):
        if role == QtCore.Qt.EditRole:
            return self.model_data[index.row()]

    def rowCount(self, parent=QtCore.QModelIndex()):  # pylint: disable=C0103
        return len(self.model_data)

    def flags(self, index):
        return QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemNeverHasChildren


class CustomList(QtWidgets.QListView):

    def __init__(self, parent=None):
        super(CustomList, self).__init__(parent)
        self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
        self.setVerticalScrollMode(self.ScrollPerPixel)

        self.setStyleSheet('''
            QListView::item {
                background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                stop: 0 #FFFFFF, stop: 1 #E0E0E0);
            }
            QListView::item:selected:!active {
                background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                stop: 0 #FFFFFF, stop: 1 #E0E0E0);
            }
            QListView::item:selected:active {
                background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                stop: 0 #FFFFFF, stop: 1 #E0E0E0);
            }''')

        self.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)

        self.my_delegate = CustomDelegate()
        self.setItemDelegate(self.my_delegate)

        self.data_model = CustomModel(self)
        self.setModel(self.data_model)

        for row in range(self.model().rowCount(None)):
            self.openPersistentEditor(self.model().createIndex(row, 0))

    def scrollContentsBy(self, dx, dy):  # pylint: disable=C0103
        super(CustomList, self).scrollContentsBy(dx, dy)
        # self.itemDelegate().updateHeaderPosition()


class QListViewTest(QtWidgets.QWidget):
    """
    测试主窗口
    """

    def __init__(self, parent=None):
        super(QListViewTest, self).__init__(parent)

        self.setWindowTitle("QListViewTest例子")
        self.resize(760, 660)

        self.list = CustomList()
        self.list.setUpdatesEnabled(True)
        self.list.setViewMode(QtWidgets.QListView.ListMode)
        add_btn = QtWidgets.QPushButton("添加")
        add_btn.clicked.connect(self.add_row)

        self.head_view = CustomItemHeader()

        _vb1 = QtWidgets.QVBoxLayout()
        _vb1.setSpacing(0)
        _vb1.addWidget(self.head_view)
        _vb1.addWidget(self.list)

        _vb2 = QtWidgets.QVBoxLayout()
        _vb2.addLayout(_vb1)
        _vb2.addWidget(add_btn)
        self.setLayout(_vb2)

    def add_row(self):
        value = {"name": "《水浒传》", "auth": "未知", "info": "一群人的故事", "detail": '''《水浒传》是由中央电视台与中国电视剧制作中心联合出品的43集电视连续剧，
根据明代施耐庵的同名小说改编。
[1]  由张绍林执导，杨争光 、冉平改编，李雪健、周野芒、臧金生、
丁海峰、赵小锐领衔主演。'''}

        index = self.list.data_model.add_data(value)
        self.list.openPersistentEditor(index)
        self.list.my_delegate.sizeHintChanged.emit(index)


if __name__ == '__main__':
    APP = QtWidgets.QApplication(sys.argv)
    QtWidgets.QApplication.setStyle("Fusion")
    WIN = QListViewTest()
    WIN.show()
    sys.exit(APP.exec_())
